﻿#include "MainWindow.h"
#include "libgit2_add.h"
#include "libgit2_branch.h"
#include "libgit2_clone.h"
#include "libgit2_commit.h"
#include "libgit2_commit_dlg.h"
#include "libgit2_diff.h"
#include "libgit2_fetch_pull.h"
#include "libgit2_init.h"
#include "libgit2_merge.h"
#include "libgit2_push.h"
#include "libgit2_rebase.h"
#include "libgit2_remote.h"
#include "libgit2_status.h"
#include "libgit2_tag.h"
#include "ui_MainWindow.h"
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QFileDialog>
#include <QInputDialog>
#include <QMessageBox>
#include <QRegExp>
#include <QStandardPaths>
#include <QTreeWidgetItem>
//#include <git2.h>
//#include <iostream>
const char *path = "D:/Lingoing/Desktop/242452/1/demo111";
//const char* path = "D:/Lingoing/Desktop/ddd";
const char* clone_path = "D:/Lingoing/Desktop/ddd/clone";
const char* private_key = "C:/Users/14122/.ssh/id_rsa";
const char* repository = "git@gitee.com:lingoing/demo111.git";
QString new_project_path;
MainWindow::MainWindow(QWidget* parent)
	: QMainWindow(parent)
	, ui(new Ui::MainWindow)
{
	ui->setupUi(this);

	ui->treeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
	connect(ui->treeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(RightClicked(QPoint)));

	connect(ui->delete_projectAction, SIGNAL(triggered(bool)), this, SLOT(delete_project()));
	connect(ui->create_branchAction, SIGNAL(triggered(bool)), this, SLOT(create_branch()));
	connect(ui->delete_branchAction, SIGNAL(triggered(bool)), this, SLOT(delete_branch()));
	connect(ui->init_pushButton, &QPushButton::clicked, [=]() {
		new_project_path = init_repository();
	});
	connect(ui->clone_pushButton, &QPushButton::clicked, [=]() {
		new_project_path = clone_repository();
	});
	connect(ui->commit_pushButton, &QPushButton::clicked, [=]() {
		commit_repository();
	});
	connect(ui->push_pushButton, &QPushButton::clicked, [=]() {
		push_repository();
	});
	//    connect(ui->branch_pushButton, &QPushButton::clicked, [=]() {
	//        QDir dir(new_project_path);
	//        dir.removeRecursively();
	//    });
}

MainWindow::~MainWindow()
{
	delete ui;
}

QString MainWindow::init_repository()
{
	libgit2_init* init = new libgit2_init;
reset:
	bool project_name_ok;

	QString text = QInputDialog::getText(this, QStringLiteral("提示"), QStringLiteral("请输入项目名称"), QLineEdit::Normal, NULL, &project_name_ok);

	QDir* t = new QDir;
	QString project_path = "";
	if (project_name_ok) {
		QMessageBox msg;
		msg.setWindowTitle(QStringLiteral("提示"));
		msg.setText(QStringLiteral("请选择版本库创建路径(默认为桌面)"));
		msg.setStandardButtons(QMessageBox::Reset | QMessageBox::Ok | QMessageBox::Ignore);
		msg.setButtonText(QMessageBox::Reset, QStringLiteral("返回上一步"));
		msg.setButtonText(QMessageBox::Ok, QStringLiteral("桌面"));
		msg.setButtonText(QMessageBox::Ignore, QStringLiteral("其他路径"));
		msg.resize(100, 60);
		int ret = msg.exec();
		if (ret == QMessageBox::Reset) {
			delete t;
			goto reset;
		}
		else if (ret == QMessageBox::Ok) {
			QString desktop_path = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
			project_path = desktop_path + "/" + text;
			bool exist = t->exists(project_path);
			if (exist) {
				QMessageBox::warning(this, QStringLiteral("创建文件夹"), QStringLiteral("文件夹已存在"));
				delete t;
				delete init;
				return "";
			}
			else {
				t->mkdir(project_path);
				init->init(project_path.toStdString().c_str());
				QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("版本库创建成功"));
				ui->treeWidget->addTopLevelItem(new QTreeWidgetItem(QStringList() << text + "[master]  " + QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz")));

				delete init;
				return project_path;
			}

		}
		else if (ret == QMessageBox::Ignore) {

			QString filePath = QFileDialog::getExistingDirectory(this, QStringLiteral("请选择文件保存路径…"), "./");
			project_path = filePath + "/" + text;
			bool exist = t->exists(project_path);
			if (exist) {
				QMessageBox::warning(this, QStringLiteral("创建文件夹"), QStringLiteral("文件夹已存在"));
				delete t;
				delete init;
				return "";
			}
			else {
				t->mkdir(project_path);
				init->init(project_path.toStdString().c_str());
				QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("版本库创建成功"));
				ui->treeWidget->addTopLevelItem(new QTreeWidgetItem(QStringList() << text + "[master]  " + QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz")));

				delete t;
				delete init;
				return project_path;
			}
		}
		else {
			delete t;
			delete init;
		}
	}
	else {
		delete t;
		delete init;
		return "";
	}
	return "";
}

QString MainWindow::clone_repository()
{
	libgit2_clone* clone = new libgit2_clone;
reset:
	bool project_name_ok;
	QString text = QInputDialog::getText(this, QStringLiteral("提示"), QStringLiteral("请输入项目地址"), QLineEdit::Normal, NULL, &project_name_ok);
	QDir* t = new QDir;
	QString project_path = "";
	if (project_name_ok) {
		QRegularExpression rx("(?<=/)[^/]+(?=.git)");
		QRegularExpressionMatch match = rx.match(text);
		QMessageBox msg;
		msg.setWindowTitle(QStringLiteral("提示"));
		msg.setText(QStringLiteral("请选择克隆路径(默认为桌面)"));
		msg.setStandardButtons(QMessageBox::Reset | QMessageBox::Ok | QMessageBox::Ignore);
		msg.setButtonText(QMessageBox::Reset, QStringLiteral("返回上一步"));
		msg.setButtonText(QMessageBox::Ok, QStringLiteral("桌面"));
		msg.setButtonText(QMessageBox::Ignore, QStringLiteral("其他路径"));
		msg.resize(100, 60);
		int ret = msg.exec();
		if (ret == QMessageBox::Reset) {
			delete t;
			goto reset;
		}
		else if (ret == QMessageBox::Ok) {
			QString desktop_path = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);

			project_path = desktop_path + "/" + match.captured(0);
			qDebug() << project_path;
			bool exist = t->exists(project_path);
			if (exist) {
				QMessageBox::warning(this, QStringLiteral("创建文件夹"), QStringLiteral("文件夹已存在"));
				delete t;
				delete clone;
				return "";
			}
			else {
				t->mkdir(project_path);
				clone->clone(project_path.toStdString().c_str(), text.toStdString().c_str());
				QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("项目克隆成功"));
				/*QDir dir(project_path);
				QFileInfoList info_list = dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
				QListIterator<QFileInfo> i(info_list);
				QStringList dir_list, file_list;
				while (i.hasNext()) {
					QFileInfo info = i.next();
					if (info.isDir()) {
						dir_list << QDir(info.absoluteFilePath()).dirName();
					}
					if (info.isFile()) {
						file_list << info.fileName();
					}
				}*/
				ui->treeWidget->addTopLevelItem(new QTreeWidgetItem(QStringList() << match.captured(0) + "[master]  " + QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz")));

				delete clone;
				return project_path;
			}

		}
		else if (ret == QMessageBox::Ignore) {

			QString filePath = QFileDialog::getExistingDirectory(this, QStringLiteral("请选择文件保存路径…"), "./");

			project_path = filePath + "/" + match.captured(0);
			bool exist = t->exists(project_path);
			if (exist) {
				QMessageBox::warning(this, QStringLiteral("创建文件夹"), QStringLiteral("文件夹已存在"));
				delete t;
				delete clone;
				return "";
			}
			else {
				t->mkdir(project_path);
				clone->clone(project_path.toStdString().c_str(), text.toStdString().c_str());
				QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("项目克隆成功"));
				ui->treeWidget->addTopLevelItem(new QTreeWidgetItem(QStringList() << match.captured(0) + "[master]  " + QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz")));

				delete t;
				delete clone;
				return project_path;
			}
		}
		else {
			delete t;
			delete clone;
		}
	}
	else {
		delete t;
		delete clone;
		return "";
	}
	return "";
}

QString MainWindow::commit_repository()
{
	libgit2_commit_dlg dlg;
	if (dlg.getCommitPath() != "") {
		dlg.setWindowTitle(QStringLiteral("提交信息"));
		//dlg.setPath(path);
		dlg.exec();
		QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("提交成功"));
	}
	else {
		dlg.reject();
	}


	return "";
}

QString MainWindow::push_repository()
{
	QString filePath = QFileDialog::getExistingDirectory(this, QStringLiteral("请选择需要推送的项目路径…"), "./");
	libgit2_push *push = new libgit2_push;
	push->push(filePath.toStdString().c_str());
	QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("推送成功"));
	delete push;
	return "";
}

void MainWindow::RightClicked(const QPoint& pos)
{
	QTreeWidgetItem* item = ui->treeWidget->itemAt(pos);
	QMenu rightMent(ui->treeWidget);
	if (item->parent() == nullptr) {
		rightMent.addAction(ui->delete_projectAction);
		rightMent.addAction(ui->create_branchAction);
	}
	else if (item->parent() != nullptr && item->parent()->parent() == nullptr) {
		rightMent.addAction(ui->delete_branchAction);
	}
	else {
		return;
	}
	rightMent.exec(QCursor::pos());
}

void MainWindow::create_branch()
{
	libgit2_branch* branch = new libgit2_branch;
	bool project_name_ok;
	QString text = QInputDialog::getText(this, QStringLiteral("提示"), QStringLiteral("请输入项目名称"), QLineEdit::Normal, NULL, &project_name_ok);
	if (project_name_ok) {
		branch->branch(new_project_path.toStdString().c_str(), text.toStdString().c_str(), "");
	}
	else {
		delete branch;
	}
}

void MainWindow::delete_project()
{
	QDir dir(new_project_path);
	dir.removeRecursively();
	delete ui->treeWidget->takeTopLevelItem(ui->treeWidget->currentIndex().row());
}

void MainWindow::delete_branch()
{
}
